import { useEffect } from "react";
import { useReactive } from "ahooks";
import { notification } from "antd";

export default function globalModel() {
	let state = useReactive({
		runEnv: "dev",
		feedBackOptions: [
			{ key: 1001, title: "需求" },
			{ key: 1002, title: "建议" },
			{ key: 1003, title: "问题" },
		],
	});

	const loadFeedbackOptions = async () => {
		const { servers } = await electron.getGlobal("personInfo");
		let server = servers.find((item) => item.type === "bnt-application-operation-center-service");
		if (server?.url) {
			let url = server.url + "/public/feedback.json";
			fetch(url)
				.then((res) => (res.status === 200 ? res.json() : []))
				.then((data) => (state.feedBackOptions = data))
				.catch((error) => console.log(error));
		}
	};

	const getShareObjectFromMain = async () => {
		const remoteSharedObject = await electron.getGlobal("sharedObject");
		for (let key in remoteSharedObject) {
			state[key] = remoteSharedObject[key];
		}
	};

	useEffect(() => {
		getShareObjectFromMain();
		document.title = "反馈";
		loadFeedbackOptions();
	}, []);

	const setSharedObjectValue = (obj) => {
		for (let key in obj) {
			state[key] = obj[key];
		}
	};

	const remoteData = async (options) => {
		// if (options.object === "bnt-application-operation-center-service") {
		// 	options.serviceUrl = "http://127.0.0.1:9021";
		// }
		let response = await electron.requestRemoteData(options);
		if (response.statusCode === 0) {
			return response.result ? response.result : true;
		} else if (response.statusCode === 1) {
			let msgs = [response.message];
			if (Array.isArray(response.result)) msgs = msgs.concat(response.result);
			if (typeof response.result === "string") msgs.push(response.result);
			notification.error({ message: "登录过期了", description: msgs.join("；") });
			state.mainWindow && state.mainWindow.webContents.send("user-exit-login");
			return null;
		} else if (response.statusCode >= 400) {
			let msgs = [response.message];
			if (Array.isArray(response.result)) msgs = msgs.concat(response.result);
			if (typeof response.result === "string") msgs.push(response.result);
			options.showError !== false && notification.error({ message: "错误信息", description: msgs.join("；") });
			return null;
		} else {
			return null;
		}
	};

	return { ...state, setSharedObjectValue, remoteData };
}
